#include "execution/executors/topn_executor.h"

namespace bustub {

TopNExecutor::TopNExecutor(ExecutorContext *exec_ctx, const TopNPlanNode *plan,
                           std::unique_ptr<AbstractExecutor> &&child_executor)
    : AbstractExecutor(exec_ctx),
      plan_(plan),
      child_executor_(std::move(child_executor))
// res_(plan)
{}

void TopNExecutor::Init() {
  LOG_DEBUG("Init");
  child_executor_->Init();
  cursor_ = 0;
  Tuple tuple;
  RID rid;
  std::priority_queue<TupleWrapper> empty;
  res_.swap(empty);
  while (child_executor_->Next(&tuple, &rid)) {
    TupleWrapper tw{plan_, tuple};
    res_.push(tw);
  }
}

auto TopNExecutor::Next(Tuple *tuple, RID *rid) -> bool {
  if (cursor_ >= plan_->GetN() || res_.empty()) {
    return false;
  }
  *tuple = res_.top().tuple_;
  res_.pop();
  *rid = tuple->GetRid();
  cursor_++;
  return true;
}

auto TopNExecutor::GetNumInHeap() -> size_t { return cursor_; };

}  // namespace bustub
